package com.esun.server.config;

import com.github.pagehelper.util.StringUtil;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign配置类
 *
 * @author zzg
 * @Date 2021-01-11
 */
@Configuration
public class FeignConfig {
	/**
	 * 从请求中获取 Authorization设置到feign请求中
	 *
	 * @return
	 */
	@Bean
	public RequestInterceptor forbpmInterceptor() {
		return requestTemplate -> {
			String token = getRequest().getHeader("Access-Token");
			// 1.请求中有token信息时复制过来
			if (StringUtil.isNotEmpty(token)) {
				requestTemplate.header("third-token", token);
				requestTemplate.header("Authorization", token);
			}
		};
	}

	/**
	 * 获取当前请求的request对象
	 *
	 * @return
	 */
	public HttpServletRequest getRequest() {
		RequestAttributes requestAttributes;
		try {
			requestAttributes = RequestContextHolder.currentRequestAttributes();
		} catch (IllegalStateException e) {
			return null;
		}
		return ((ServletRequestAttributes) requestAttributes).getRequest();
	}

}
